package org.sample.service.impl;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.sample.commons.bean.BeanUtils;
import org.sample.dao.LogDao;
import org.sample.entity.Log;
import org.sample.service.LogService;
import org.sample.web.AlarmMessageQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

@Service
public class LogServiceImpl implements LogService {

    @Autowired
    private LogDao dao;

    private AlarmMessageQueue messageQueue = AlarmMessageQueue.Instance;

    private static final ExecutorService pool = Executors.newSingleThreadExecutor();

    @PostConstruct
    private void processLog() {
        pool.execute(() -> {
            while (true) {
                try {
                    Log log = messageQueue.poll();
                    dao.save(log);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public List<Log> getIdNameList() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void logicalDelete(Integer id) {
        Log entity = dao.getOne(id);
        entity.setDeleted(true);
        dao.save(entity);
    }

    @Override
    public Log saveNotNull(Log entity) {
        if (entity.getId() == null) {
            return dao.save(entity);
        }
        Log oldEntity = dao.getOne(entity.getId());
        BeanUtils.copyBeanNotNull(entity, oldEntity);
        return dao.save(oldEntity);
    }

}